package com.burial.service.impl;

import cn.hutool.json.JSONUtil;
import com.burial.bo.OrderProductBo;
import com.burial.common.result.Result;
import com.burial.dto.OrderDTO;
import com.burial.entity.Order;
import com.burial.entity.OrderInfo;
import com.burial.mapper.OrderInfoMapper;
import com.burial.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.burial.service.OrderService;
import com.cqgc.service.UserService;
import com.tsl.domain.pojo.TbSKU;
import com.tsl.service.ITbProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单详情信息表 服务实现类
 * </p>
 *
 * @author burial
 * @since 2024-04-18
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderService orderService;
    @Resource
    private UserService userService;

    @Resource
    private ITbProductService productService;

    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    @Override
    public OrderDTO findOrderInfo(Integer oid) {

        String key="orderInfo:"+oid;

        String orderDtoStr = stringRedisTemplate.opsForValue().get(key);
        if (orderDtoStr!=null&&orderDtoStr!=""){
            return JSONUtil.toBean(orderDtoStr,OrderDTO.class);
        }
        Order order = orderService.getById(oid);
        if (order==null){
            return null;
        }
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setPurchase(userService.getById(order.getPurchaseId()));
        orderDTO.setSupplier(userService.getById(order.getSupplierId()));
        if (orderDTO.getPurchase()==null||orderDTO.getSupplier()==null){
            return null;
        }
        List<OrderInfo> orderInfos = query().eq("oid", order.getOid()).list();
        if (orderInfos==null||orderInfos.size()==0){
            return null;
        }
        List<OrderProductBo> orderProductBos = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfos) {
            TbSKU product = productService.selectById(orderInfo.getPid());
            if (product==null){
                return null;
            }
            OrderProductBo orderProductBo=new OrderProductBo();
            orderProductBo.setId(orderInfo.getId());
            orderProductBo.setProduct(product);
            orderProductBo.setOid(orderInfo.getOid());
            orderProductBo.setPcount(orderInfo.getPcount());
            orderProductBos.add(orderProductBo);
        }

        orderDTO.setOrderInfoList(orderProductBos);

        orderDtoStr = JSONUtil.toJsonStr(orderDTO);

        stringRedisTemplate.opsForValue().set(key,orderDtoStr);

        return orderDTO;
    }
}
